package org.carl.base.driving.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.carl.base.driving.annotation.EnableDriving;
import org.carl.base.driving.bean.DrivingBeanConfig;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@Slf4j
@ConditionalOnBean(annotation = EnableDriving.class)
public class DriveConfig {
    /**
     * 驱动 - 消息队列名称（必须为每个业务系统建立一个队列）
     */
    @Value("${driving.message.queue.name:}")
    private String messageQueueName;


    /**
     * 驱动 - 本服务routingKey
     */
    @Value("${driving.message.routingKey:}")
    private String routingKey;
    /**
     * 应用名称
     */
    @Value("${spring.application.name:}")
    private String applicationName;
    /**
     * 交换机
     */
    @Value("${spring.rabbitmq.template.exchange:}")
    private String exchangeName;
    @Autowired
    private AmqpAdmin amqpAdmin;

    /**
     * 驱动配置
     * @return
     */
    @Bean
    public DrivingBeanConfig drivingBeanConfig(){
        if(StrUtil.isBlank(applicationName)){
            log.error("请配置spring.application.name");
            System.exit(1);
        }
        DrivingBeanConfig drivingBeanConfig=new DrivingBeanConfig();
        //将应用名称中的下划线或中杠转换为点.
        applicationName=StrUtil.trim(applicationName.toLowerCase().replaceAll("[-|_]",StrUtil.DOT));
        if(StrUtil.isBlank(messageQueueName)){
            messageQueueName="transaction."+applicationName+".queue";
            log.warn("MQ驱动未找到driving.message.queue.name配置,将使用默认队列名:{}",messageQueueName);
        }
        drivingBeanConfig.setMessageQueueName(messageQueueName);
        if(StrUtil.isBlank(routingKey)){
            routingKey="routing."+applicationName+".local";
            log.warn("MQ驱动未找到driving.message.routingKey配置,将使用默认routingKey:{}",routingKey);
        }
        QueueInformation queueInfo = amqpAdmin.getQueueInfo(messageQueueName);
        if(queueInfo==null){
            Queue queue=new Queue(messageQueueName,true,false,false);
            amqpAdmin.declareQueue(queue);
            log.info("queue:{}不存在执行初始化queue",messageQueueName);
        }
        amqpAdmin.declareBinding(new Binding(messageQueueName, Binding.DestinationType.QUEUE,exchangeName,routingKey,null));
        log.info("exchange:{},routingKey:{},queue:{}执行绑定.",exchangeName,routingKey,messageQueueName);
        drivingBeanConfig.setRoutingKey(routingKey);
        return drivingBeanConfig;
    }

}
